package com.neolix.watch.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

import com.neolix.watch.R;
import com.neolix.watch.util.ErrorPopWindowsUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.neolix.watch.NeolixApplication.getInstance;

public class TestView extends View implements View.OnTouchListener {
    private List<Integer> stepsList = new ArrayList<Integer>();
    private String TAG = TestView.class.getSimpleName();
    private int screenWidth;
    private int screenHeight;
    private List<PointF> pointList;

    private OnSelectListener onSelectListener;

    private Point maxPopWindowPoint;

    public TestView(Context context) {
        super(context);
        initUi();
    }

    public TestView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initUi();
    }

    public TestView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initUi();
    }

    public void setOnSelectListener(OnSelectListener onSelectListener) {
        this.onSelectListener = onSelectListener;
    }

    public Point getMaxPopWindowPoint() {
        return maxPopWindowPoint;
    }

    private void initUi() {
        DisplayMetrics dm = new DisplayMetrics();
        dm = this.getResources().getDisplayMetrics();
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;
        setOnTouchListener(this);
    }

    public void setData(List<Integer> stepsList) {
        this.stepsList = stepsList;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(getInstance().getResources().getColor(R.color.main_activity_menu));
        PointF lastPoint = null;

        int height = getHeight();
        int width = getWidth();

        Log.i(TAG, "height:" + height + "    width:" + width);

        //Calculation width info
        int count = this.stepsList.size();
        int eachWidth = width / count;
        int startValue = eachWidth / 2;
        int padding = 10;

        //Calculation height info
        Integer max = Collections.max(stepsList);
        Integer min = Collections.min(stepsList);

        float eachHeight = (float) height / (max - min + 1);

        //TODO if max-min=0
        //Calculation path
        Path path = new Path();
        float yValue;
        float xValue;

        pointList = new ArrayList<PointF>();
        PointF po;
        for (int i = 0; i < count; i++) {
            xValue = startValue + (i) * eachWidth;

            if (max - min == 0 && max != 0)
                // 如果每个点都一样则画在最上面
                yValue = padding;
            else if (max - min == 0 && max == 0) {
                // 如果每个点都一样则画在最下面
                yValue = height - padding;
            } else {
                yValue = height - (int) ((stepsList.get(i) - min) * eachHeight);
                if (stepsList.get(i).equals(max))
                    //最大 则和TOP留出padding 不然 画笔比较粗时，有部分看不见
                    yValue += padding;
                else if (stepsList.get(i).equals(min))
                    //最小 则和BOTTOM留出padding 不然 画笔比较粗时，有部分看不见
                    yValue -= padding;
            }

            po = new PointF(xValue, yValue);
            pointList.add(po);

            if (i == 0)
                path.moveTo(xValue, yValue);
            else {

                float middleX = lastPoint.x + (xValue - lastPoint.x) / 2;
                if (yValue > lastPoint.y)
                    middleX += eachWidth / 2;
                else
                    middleX -= eachWidth / 2;
                float middleY = lastPoint.y + ((yValue - lastPoint.y) / 2 * 1.5f);
//                path.quadTo(middleX + 5, middleY, xValue, yValue);
                path.lineTo(xValue, yValue);
            }

            lastPoint = po;

            Log.i(TAG, "x:" + xValue + "    y:" + yValue);
        }

        //begin draw
        Paint paint = new Paint();

        paint.setColor(getInstance().getResources().getColor(R.color.curve_color));
        paint.setAntiAlias(true);
        paint.setStrokeWidth(5);
        paint.setStyle(Paint.Style.STROKE);

        canvas.drawPath(path, paint);

        for (int i = 0; i < count; i++) {
            //画出小圆
            paint.setColor(getInstance().getResources().getColor(R.color.text_color_yellow));
            paint.setAntiAlias(true);
            paint.setStrokeWidth(1);
            paint.setStyle(Paint.Style.FILL);
//            Shader mShader = new LinearGradient(0, 0, 40, 60, new int[]{
//                    Color.YELLOW, Color.GRAY}, null,
//                    Shader.TileMode.REPEAT
//            );

            Shader mShader = new RadialGradient(pointList.get(i).x, pointList.get(i).y, 5, new int[]{getInstance().getResources().getColor(R.color.curve_color),
                    getInstance().getResources().getColor(R.color.text_color_yellow)}, null, Shader.TileMode.REPEAT);
            paint.setShader(mShader);

            canvas.drawCircle(pointList.get(i).x, pointList.get(i).y, 10, paint);
        }

        int index = getMaxPointIndex();
        if (index >= 0) {
            int[] location = new int[2];
            getLocationOnScreen(location);
            int x = (int) pointList.get(index).x - screenWidth / 2;
            int y = (int) pointList.get(index).y + location[1] - screenHeight / 2;
            maxPopWindowPoint = new Point(x, y);
        }
    }

    private int getMaxPointIndex() {
        Integer max = Collections.max(stepsList);
        return stepsList.indexOf(max);
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:// 按下
                int index = getNearPointIndex(event.getX(), event.getY());
                if (index >= 0) {
                    int[] location = new int[2];
                    view.getLocationOnScreen(location);
                    int x = (int) pointList.get(index).x - screenWidth / 2;
                    int y = (int) pointList.get(index).y + location[1] - screenHeight / 2;
                    ErrorPopWindowsUtil.createPointPopWindowAndShowAt(R.drawable.ic_best_point, this, x, y);
                    Log.i("touch", "X:" + x + "Y:" + y + "       view location y:" + location[1] + " event.getY()" + event.getY());
                    if (onSelectListener != null)
                        onSelectListener.onSelect(10000, stepsList.get(index));
                }
                break;
            default:
        }
        return true;
    }

    private int getNearPointIndex(final float x, final float y) {
        int index = -1;
        for (int i = 0; i < stepsList.size(); i++) {
            PointF pointF = pointList.get(i);
            int offset = 40;
            if (x >= pointF.x - offset && x <= pointF.x + offset
                    && y >= pointF.y - offset && y <= pointF.y + offset) {
                index = i;
                break;
            }
        }
        return index;
    }

    public interface OnSelectListener {
        void onSelect(int goalSteps, int currentSteps);
    }
}
